import mapboxgl from "mapbox-gl";
import * as turf from "@turf/turf";
// import mapServe from "@/config/mapserve";
import gateway from "../../../public/static/config";
import CoordinateTransformation from "./CoordinateTransformation";
// import DataTool from "./DataTool";

mapboxgl.accessToken =
  "pk.eyJ1IjoieWFvbGlubGl1IiwiYSI6ImNraWk1dTdjZzB1bmMyc3M1dXMzY3ZmN20ifQ.bSwoU1Epu_mlGZqpcdcWRg";
const defaultOptions = {
  container: "mapContainer",
  //style: "mapbox://styles/mapbox/streets-v10",
  style: {
    version: 8,
    //   // glyphs: "http://172.23.144.1:11000/fonts/mapbox/{fontstack}/{range}.pbf",
    // glyphs: "mapbox://fonts/mapbox/{fontstack}/{range}.pbf",
    sources: {
      baseMap: {
        type: "raster",
        tiles: [
          // mapServe.mapURL
          gateway.mapUrl,
        ],
        tileSize: 256,
      },
    },
    layers: [
      {
        id: "base-map",
        type: "raster",
        source: "baseMap",
        minzoom: 0,
        maxzoom: 22,
      },
    ],
  },
  // style: 'mapbox://styles/mapbox/streets-v11',

  // center: [116.195655, 19.552066],
  center: [79.818147, 33.453021],
  minzoom: 0,
  zoom: 10,
  maxzoom: 22,
  preserveDrawingBuffer: true, // 这个需要开启，才能获取正确的base64
};

class baseMap {
  options: any;
  map: any;
  constructor(options: any) {
    if (options.map) {
      this.map = options.map;
    } else if (options.map == undefined) {
      this.options = extend(Object.create(defaultOptions), options);
      this.map = this.initMap();
    }
  }
  //初始化底图
  initMap() {
    return new mapboxgl.Map(this.options);
  }
  //加载影像图层
  addImageLayer(options: any) {
    // this.map.flyTo({ center: options.center, zoom: 14 });
    this.map.flyTo({
      center: options.center,
      essential: true,
    });

    this.map.setStyle({
      metadata: {},
      sources: {
        baseMap: {
          tiles: [options.mapUrl],
          tileSize: 256,
          type: "raster",
        },
      },
      // glyphs: "http://172.23.144.1:11000/fonts/mapbox/{fontstack}/{range}.pbf",
      glyphs: "mapbox://fonts/mapbox/{fontstack}/{range}.pbf",
      center: options.center,
      name: "China Basic Map",
      layers: [
        {
          id: "base-map",
          source: "baseMap",
          type: "raster",
          minzoom: 0,
          maxzoom: 22,
        },
      ],
      // zoom: 14,
      // id: "36k17k9qb",
      version: 8,
      minzoom: 0,
      zoom: 8,
      maxzoom: 22,
      id: "36k17k9qb",
      preserveDrawingBuffer: true, // 这个需要开启，才能获取正确的base64
      maxBounds: options.maxBounds, // Set the map's geographical boundaries.
      // epsg: 4326, // wgs84的epsg
    });
  }
  //加载图片
  addLayersImage(options: any) {
    // this.map.flyTo({ center: options.center, zoom: 14 });
    this.map.flyTo({
      center: options.center,
      essential: true,
    });

    this.map.addSource("imageLayers", {
      type: "image",
      url: options.mapUrl,
      coordinates: options.coordinates,
      //  [
      //   //左下角开始 逆时针
      //   [114.931, 35.9952],
      //   [115.742, 35.8687],
      //   [115.897, 36.475],
      //   [115.079, 36.6019],
      // ],
    });
    this.map.addLayer({
      id: "imageLayersId",
      type: "raster",
      source: "imageLayers",
      minzoom: 0,
      zoom: 6,
      maxzoom: 24,
    });
  }

  //移除图层
  removeLayer(id: any) {
    if (this.map.getLayer(id)) {
      this.map.removeLayer(id);
    }
  }
  //移除数据源
  removeDataSource(id: any) {
    if (this.map.getSource(id)) {
      this.map.removeSource(id);
    }
  }
  removeimage(id: any) {
    if (this.map.hasimage(id)) {
      this.map.removeimage(id);
    }
  }
  //FeatureCollection格式数据-地图加线
  addArea(datas: any, options: any) {
    const defaultOptions = {
      layerId: "mapPolygon",
      description: "description",
      iconImgUrl:
        "data: image / png; base64, iVBORw0KGgoAAAANSUhEUgAAACwAAAA4CAYAAACGwxqMAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAARZSURBVHgBzZrPbxtVEMe/ sw5UVBE1LSCQqEghiAOXdVOQ4FA2EoeecCz1TiLxBzg3bk3 / gpS / IO6NQ6UkPeXWTSUuIDc + 8qMqq3IgAloMRA0p8b7OrH/Ubmzvvtl1sx/Jsnf37b6vx / PmzZtnQgq89Z0iv7kglOFgBgaugZFzxU6TJr8CImoiRIOvb / Jxw6 + UmlBCUMBCPRRwxRjj9olLjjE1Ms51Fu7DEivBfUI9ZENAoBW / XLqe9IZEglnoDAtdy1DooAiiDbT + W / YrHwdxbZ24Bt56fdE4ZmdSYgV + 9oJxTuxwX9W4tmMFe5v1FePQGjR + ak + R + 1qVPsc1GukSkVjQFRwDBHPVL8 + tDL82hOMU22WU6COCvZv1qjG0ihxgEC7eLl8YiCADgiUayADD8 / HZJDQpPCj1R4 / BQVeAWDYvYoWiKZxY6z / RExyFLw4vyBsGnrf + vdc9nOqdd9INMvfVaVw6ewbumWm8cfLF6Nzdv / dx9599bN1 / gMaDPWgxhYJo8 + Vz5MMy5bLv3oICEfdV6e1I6Di2fn2I2o + /YffRY2igsDXvVz702y5RwBdQIGKvffJerFjh0tnTUduu9W3pWBkkKSJb9y8o+OazD6wFiIW/9H / A3mELlnDEoHNiYRcKFt9 / U2UtuefyO69BAUevQ9eJkm8F8hNrufzu65ieKsAamio7HNisLSwRQeuLwvQLBcyeegm28Mw343DstZ4oZl + 27 + zIMxSCOXF2xYdnYIlYKC3KZxRFsLWF9 / 63HuFZPaMYu + IYhsxeaZFZUIMItl5yS2dprCyxWDlVNx1etVoLFrE37v0OLZJbqDAIJA43oODGvT9UeYHcU / tpF0qaDldkAigQK1e//dlKtLSVe7SwNzQcmMNNKNndbwtI8hM3/vy3/QX3ddlaBMHvJj+/IOVKI8qH3zodTQizp05G53YfHUSDa+v+w1T5cE9vSK9E+fCnN+/cksweeYbrcdsLc0tRHKZW6ypyjuNQTd57q+acWznYLp8/Jx96M12erSwVzqef+8illY3ZYN+tdA8Hcglq0RIUU/UEaZJ5vNx/YkAwV8QDCs0ycgK7QvXZmvGRbM2vzNV4n2IFx4xoGFaZH1NuvcPCdcv/1BD77edP/baf0flwSFINVyVGKQmo5SyNujhSsGxN8VQo3zLA84PH0MH8uG2x2E0Zb/071zhTUsaadFXzSGl1GLFLJL/yUYPCcAkTRvrIZBdJ8CsXNiYZOaKIwH0kaWu1sXhxo77Ke2qxW1M2cF3k2u2FucSx33rrNtPp28DfXjg/b3OL9TKfp++sIkdAhiq2N1kL7oQ7sUoAPbHhaxSq3XyhE+52oIDCw5JEHyhQVX6Edrgz1uGOK5BVrVhBLViwTZSkLW8Ufo0UqF2inySJkm34GkUqC/eIT5QaWYgVMhEckyhJRLAOX6PIxCW6DNmrTpTQ2JCNS3RoL7FaPWsmTWiOHfkLw8XN+kT+b/EEhgjdVdsknN0AAAAASUVORK5CYII=",
    };

    options = extend(Object.create(defaultOptions), options);
    this.removeLayer(options.layerId);

    this.removeDataSource(options.layerId);
    // this.removeLayer("mapPolygon");

    // this.removeDataSource("mapPolygon");
    // map.removelayer("mapLineString");
    // map.removesource("mapLineString");
    this.map.addSource(options.layerId, {
      type: "geojson",
      data: datas,
    });
    if (!options.fillColor) {
      options.fillColor = "#E8D072";
    }
    this.map.addLayer({
      id: options.layerId,
      type: "fill",
      source: options.layerId,
      // layout: {
      //   "line-join": "round",
      //   "line-cap": "round"
      // },
      paint: {
        "fill-color": options.fillColor,
        "fill-opacity": 0.8,
      },
    });
    let _this = this;
    _this.map.on("click", options.layerId, function () {
      // var features = _this.map.queryRenderedFeatures(e.point, {
      //   layers: [options.layerId]
      // });
    });
  }

  //FeatureCollection格式数据-地图加线

  addLineString(datas: any, options: any) {
    const defaultOptions = {
      lineColor: "#ffff00",
      layerId: "mapLineString",
      name: "poi_name",
      time: "time",
      description: "description",
      iconImgUrl:
        "data: image / png; base64, iVBORw0KGgoAAAANSUhEUgAAACwAAAA4CAYAAACGwxqMAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAARZSURBVHgBzZrPbxtVEMe/ sw5UVBE1LSCQqEghiAOXdVOQ4FA2EoeecCz1TiLxBzg3bk3 / gpS / IO6NQ6UkPeXWTSUuIDc + 8qMqq3IgAloMRA0p8b7OrH/Ubmzvvtl1sx/Jsnf37b6vx / PmzZtnQgq89Z0iv7kglOFgBgaugZFzxU6TJr8CImoiRIOvb / Jxw6 + UmlBCUMBCPRRwxRjj9olLjjE1Ms51Fu7DEivBfUI9ZENAoBW / XLqe9IZEglnoDAtdy1DooAiiDbT + W / YrHwdxbZ24Bt56fdE4ZmdSYgV + 9oJxTuxwX9W4tmMFe5v1FePQGjR + ak + R + 1qVPsc1GukSkVjQFRwDBHPVL8 + tDL82hOMU22WU6COCvZv1qjG0ihxgEC7eLl8YiCADgiUayADD8 / HZJDQpPCj1R4 / BQVeAWDYvYoWiKZxY6z / RExyFLw4vyBsGnrf + vdc9nOqdd9INMvfVaVw6ewbumWm8cfLF6Nzdv / dx9599bN1 / gMaDPWgxhYJo8 + Vz5MMy5bLv3oICEfdV6e1I6Di2fn2I2o + /YffRY2igsDXvVz702y5RwBdQIGKvffJerFjh0tnTUduu9W3pWBkkKSJb9y8o+OazD6wFiIW/9H / A3mELlnDEoHNiYRcKFt9 / U2UtuefyO69BAUevQ9eJkm8F8hNrufzu65ieKsAamio7HNisLSwRQeuLwvQLBcyeegm28Mw343DstZ4oZl + 27 + zIMxSCOXF2xYdnYIlYKC3KZxRFsLWF9 / 63HuFZPaMYu + IYhsxeaZFZUIMItl5yS2dprCyxWDlVNx1etVoLFrE37v0OLZJbqDAIJA43oODGvT9UeYHcU / tpF0qaDldkAigQK1e//dlKtLSVe7SwNzQcmMNNKNndbwtI8hM3/vy3/QX3ddlaBMHvJj+/IOVKI8qH3zodTQizp05G53YfHUSDa+v+w1T5cE9vSK9E+fCnN+/cksweeYbrcdsLc0tRHKZW6ypyjuNQTd57q+acWznYLp8/Jx96M12erSwVzqef+8illY3ZYN+tdA8Hcglq0RIUU/UEaZJ5vNx/YkAwV8QDCs0ycgK7QvXZmvGRbM2vzNV4n2IFx4xoGFaZH1NuvcPCdcv/1BD77edP/baf0flwSFINVyVGKQmo5SyNujhSsGxN8VQo3zLA84PH0MH8uG2x2E0Zb/071zhTUsaadFXzSGl1GLFLJL/yUYPCcAkTRvrIZBdJ8CsXNiYZOaKIwH0kaWu1sXhxo77Ke2qxW1M2cF3k2u2FucSx33rrNtPp28DfXjg/b3OL9TKfp++sIkdAhiq2N1kL7oQ7sUoAPbHhaxSq3XyhE+52oIDCw5JEHyhQVX6Edrgz1uGOK5BVrVhBLViwTZSkLW8Ufo0UqF2inySJkm34GkUqC/eIT5QaWYgVMhEckyhJRLAOX6PIxCW6DNmrTpTQ2JCNS3RoL7FaPWsmTWiOHfkLw8XN+kT+b/EEhgjdVdsknN0AAAAASUVORK5CYII=",
    };
    options = extend(Object.create(defaultOptions), options);
    let _this = this;
    this.removeLayer(options.layerId);

    this.removeDataSource(options.layerId);
    // map.removelayer("mapLineString");
    // map.removesource("mapLineString");
    _this.map.addSource(options.layerId, {
      type: "geojson",
      data: datas,
    });
    if (!options.lineColor) {
      options.lineColor = "#ffff00";
    }
    _this.map.addLayer({
      id: options.layerId,
      type: "line",
      source: options.layerId,
      layout: {
        "line-join": "round",
        "line-cap": "round",
      },
      paint: {
        // "line-color": "#ffff00",
        "line-color": options.lineColor,
        "line-width": 5,
        // "line-dasharray": [5, 5]
      },
      epsg: 4326, // wgs84的epsg
    });
    // _this.map.on("click", options.layerId, function(e) {
    //   // console.log(1111111111111);
    //   // let features = _this.map.querySourceFeatures(options.layerId, {
    //   //   layers: [options.layerId]
    //   // });
    //   const bbox = [
    //     [e.point.x - 5, e.point.y - 5],
    //     [e.point.x + 5, e.point.y + 5]
    //   ];
    //   let renderFeatures = _this.map.queryRenderedFeatures(bbox, {
    //     layers: [options.layerId]
    //   });
    //   console.log(renderFeatures[0], "线");
    //   let obj = {
    //     geometry: renderFeatures[0].geometry
    //   };
    //   _this.addSelectLayer(obj);
    // });
  }
  //选中某一个目标
  addSelectLayer(feature: any) {
    this.removeLayer("show_select");
    this.removeDataSource("show_select");
    // let _feature = turf.lineString(feature.geometry.coordinates[0]);
    // let _feature = feature.geometry.coordinates
    this.map.addSource("show_select", {
      type: "geojson",
      data: feature.geometry,
    });
    this.map.addLayer({
      id: "show_select",
      type: "line",
      source: "show_select",
      paint: {
        "line-color": "#00FFFF",
        "line-width": 5,

        /*"line-dasharray":[2,4]*/
      },
      layout: {
        "line-join": "round",
        "line-cap": "round",
      },
    });
  }
  addPoint(datas: any, options: any) {
    //默认参数
    let popup: null;
    // debugger;
    const defaultOptions = {
      layerId: "mapPoints",
      name: "name",
      time: "time",
      description: "description",
      iconImgUrl:
        "data: image / png; base64, iVBORw0KGgoAAAANSUhEUgAAACwAAAA4CAYAAACGwxqMAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAARZSURBVHgBzZrPbxtVEMe/ sw5UVBE1LSCQqEghiAOXdVOQ4FA2EoeecCz1TiLxBzg3bk3 / gpS / IO6NQ6UkPeXWTSUuIDc + 8qMqq3IgAloMRA0p8b7OrH/Ubmzvvtl1sx/Jsnf37b6vx / PmzZtnQgq89Z0iv7kglOFgBgaugZFzxU6TJr8CImoiRIOvb / Jxw6 + UmlBCUMBCPRRwxRjj9olLjjE1Ms51Fu7DEivBfUI9ZENAoBW / XLqe9IZEglnoDAtdy1DooAiiDbT + W / YrHwdxbZ24Bt56fdE4ZmdSYgV + 9oJxTuxwX9W4tmMFe5v1FePQGjR + ak + R + 1qVPsc1GukSkVjQFRwDBHPVL8 + tDL82hOMU22WU6COCvZv1qjG0ihxgEC7eLl8YiCADgiUayADD8 / HZJDQpPCj1R4 / BQVeAWDYvYoWiKZxY6z / RExyFLw4vyBsGnrf + vdc9nOqdd9INMvfVaVw6ewbumWm8cfLF6Nzdv / dx9599bN1 / gMaDPWgxhYJo8 + Vz5MMy5bLv3oICEfdV6e1I6Di2fn2I2o + /YffRY2igsDXvVz702y5RwBdQIGKvffJerFjh0tnTUduu9W3pWBkkKSJb9y8o+OazD6wFiIW/9H / A3mELlnDEoHNiYRcKFt9 / U2UtuefyO69BAUevQ9eJkm8F8hNrufzu65ieKsAamio7HNisLSwRQeuLwvQLBcyeegm28Mw343DstZ4oZl + 27 + zIMxSCOXF2xYdnYIlYKC3KZxRFsLWF9 / 63HuFZPaMYu + IYhsxeaZFZUIMItl5yS2dprCyxWDlVNx1etVoLFrE37v0OLZJbqDAIJA43oODGvT9UeYHcU / tpF0qaDldkAigQK1e//dlKtLSVe7SwNzQcmMNNKNndbwtI8hM3/vy3/QX3ddlaBMHvJj+/IOVKI8qH3zodTQizp05G53YfHUSDa+v+w1T5cE9vSK9E+fCnN+/cksweeYbrcdsLc0tRHKZW6ypyjuNQTd57q+acWznYLp8/Jx96M12erSwVzqef+8illY3ZYN+tdA8Hcglq0RIUU/UEaZJ5vNx/YkAwV8QDCs0ycgK7QvXZmvGRbM2vzNV4n2IFx4xoGFaZH1NuvcPCdcv/1BD77edP/baf0flwSFINVyVGKQmo5SyNujhSsGxN8VQo3zLA84PH0MH8uG2x2E0Zb/071zhTUsaadFXzSGl1GLFLJL/yUYPCcAkTRvrIZBdJ8CsXNiYZOaKIwH0kaWu1sXhxo77Ke2qxW1M2cF3k2u2FucSx33rrNtPp28DfXjg/b3OL9TKfp++sIkdAhiq2N1kL7oQ7sUoAPbHhaxSq3XyhE+52oIDCw5JEHyhQVX6Edrgz1uGOK5BVrVhBLViwTZSkLW8Ufo0UqF2inySJkm34GkUqC/eIT5QaWYgVMhEckyhJRLAOX6PIxCW6DNmrTpTQ2JCNS3RoL7FaPWsmTWiOHfkLw8XN+kT+b/EEhgjdVdsknN0AAAAASUVORK5CYII=",
    };

    options = extend(Object.create(defaultOptions), options);
    console.log(options);
    let _this = this;
    this.removeLayer(options.layerId.toString());
    this.removeDataSource(options.layerId.toString());
    // this.removeimage("customMarker")
    _this.map.loadImage(options.iconImgUrl, function (error, image) {
      // if (error) throw error;
      _this.map.addImage(options.layerId.toString(), image);
      // Add a GeoJSON source with 2 points
      _this.map.addSource(options.layerId.toString(), {
        type: "geojson",
        data: datas,
      });

      // _this.map.flyTo({ center: datas.features[0].geometry.coordinates });

      // Add a symbol layer
      if (!options.textColor) {
        options.textColor = "#ffff00";
      }
      _this.map.addLayer({
        id: options.layerId.toString(),
        type: "symbol",
        source: options.layerId.toString(),
        layout: {
          "icon-image": options.layerId.toString(),
          "icon-size": 0.6,
          "text-field": ["get", options.name],
          "text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"],
          "text-offset": [0, 1],
          "text-anchor": "top",
        },
        paint: {
          "text-color": options.textColor,
        },
        minzoom: 0,
        maxzoom: 22,
      });
    });

    _this.map.on("click", options.layerId, function (e) {
      var features = _this.map.queryRenderedFeatures(e.point, {
        layers: [options.layerId],
      });
      console.log(features, "点");
      if (features.length) {
        let el = document.createElement("div");
        el.className = "marker";
        if (popup) {
          popup.remove();
        }
        // let keysData = Object.keys(features[0].properties);
        // let valueData = features[0].properties;
        // popup = new mapboxgl.Popup({ offset: 25, className: "my-Popup" })
        //   .setLngLat(features[0].geometry.coordinates)
        //   .setHTML(
        //     `<h3>${valueData[keysData[0]]}</h3><p>${
        //       valueData[keysData[1]]
        //     }</p >`
        //   )
        //   .setMaxWidth("300px")
        //   .addTo(_this.map);
        // let marker = new mapboxgl.Marker()
        //   .setLngLat(features[0].geometry.coordinates)
        //   .setPopup(
        //     new mapboxgl.Popup({ offset: 25 }) // add popups
        //       .setHTML()
        //   )
        //   .addTo(map);
      }
    });
    // });
  }
  //FeatureCollection格式数据-地图加线
  addGeojson(datas: any, options: any) {
    let defaultoption = {
      layerId: "addGeojson",
      name: "ogc_fid",
      time: "time",
      description: "description",
      iconImgUrl:
        "data: image / png; base64, iVBORw0KGgoAAAANSUhEUgAAACwAAAA4CAYAAACGwxqMAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAARZSURBVHgBzZrPbxtVEMe/ sw5UVBE1LSCQqEghiAOXdVOQ4FA2EoeecCz1TiLxBzg3bk3 / gpS / IO6NQ6UkPeXWTSUuIDc + 8qMqq3IgAloMRA0p8b7OrH/Ubmzvvtl1sx/Jsnf37b6vx / PmzZtnQgq89Z0iv7kglOFgBgaugZFzxU6TJr8CImoiRIOvb / Jxw6 + UmlBCUMBCPRRwxRjj9olLjjE1Ms51Fu7DEivBfUI9ZENAoBW / XLqe9IZEglnoDAtdy1DooAiiDbT + W / YrHwdxbZ24Bt56fdE4ZmdSYgV + 9oJxTuxwX9W4tmMFe5v1FePQGjR + ak + R + 1qVPsc1GukSkVjQFRwDBHPVL8 + tDL82hOMU22WU6COCvZv1qjG0ihxgEC7eLl8YiCADgiUayADD8 / HZJDQpPCj1R4 / BQVeAWDYvYoWiKZxY6z / RExyFLw4vyBsGnrf + vdc9nOqdd9INMvfVaVw6ewbumWm8cfLF6Nzdv / dx9599bN1 / gMaDPWgxhYJo8 + Vz5MMy5bLv3oICEfdV6e1I6Di2fn2I2o + /YffRY2igsDXvVz702y5RwBdQIGKvffJerFjh0tnTUduu9W3pWBkkKSJb9y8o+OazD6wFiIW/9H / A3mELlnDEoHNiYRcKFt9 / U2UtuefyO69BAUevQ9eJkm8F8hNrufzu65ieKsAamio7HNisLSwRQeuLwvQLBcyeegm28Mw343DstZ4oZl + 27 + zIMxSCOXF2xYdnYIlYKC3KZxRFsLWF9 / 63HuFZPaMYu + IYhsxeaZFZUIMItl5yS2dprCyxWDlVNx1etVoLFrE37v0OLZJbqDAIJA43oODGvT9UeYHcU / tpF0qaDldkAigQK1e//dlKtLSVe7SwNzQcmMNNKNndbwtI8hM3/vy3/QX3ddlaBMHvJj+/IOVKI8qH3zodTQizp05G53YfHUSDa+v+w1T5cE9vSK9E+fCnN+/cksweeYbrcdsLc0tRHKZW6ypyjuNQTd57q+acWznYLp8/Jx96M12erSwVzqef+8illY3ZYN+tdA8Hcglq0RIUU/UEaZJ5vNx/YkAwV8QDCs0ycgK7QvXZmvGRbM2vzNV4n2IFx4xoGFaZH1NuvcPCdcv/1BD77edP/baf0flwSFINVyVGKQmo5SyNujhSsGxN8VQo3zLA84PH0MH8uG2x2E0Zb/071zhTUsaadFXzSGl1GLFLJL/yUYPCcAkTRvrIZBdJ8CsXNiYZOaKIwH0kaWu1sXhxo77Ke2qxW1M2cF3k2u2FucSx33rrNtPp28DfXjg/b3OL9TKfp++sIkdAhiq2N1kL7oQ7sUoAPbHhaxSq3XyhE+52oIDCw5JEHyhQVX6Edrgz1uGOK5BVrVhBLViwTZSkLW8Ufo0UqF2inySJkm34GkUqC/eIT5QaWYgVMhEckyhJRLAOX6PIxCW6DNmrTpTQ2JCNS3RoL7FaPWsmTWiOHfkLw8XN+kT+b/EEhgjdVdsknN0AAAAASUVORK5CYII=",
    };
    options = extend(Object.create(defaultoption), options);
    this.removeLayer(options.layerId + "Circle");
    this.removeLayer(options.layerId + "Line");
    this.removeLayer("layerFill");
    this.removeLayer("mapLineString");

    this.removeLayer(options.layerId + "_label");

    this.removeDataSource(options.layerId);
    this.removeDataSource(options.layerId + "_label");

    // let dataObj = new DataTool({
    //   datas: datas,
    //   colors: options.colors
    // }).initDataShibie();
    // if (dataObj.lineStringArr) {
    //   this.addLineString(turf.featureCollection(dataObj.lineStringArr), {});
    // }

    // map.removesource("mapLineString");
    this.map.addSource(options.layerId, {
      type: "geojson",
      data: datas,
    });
    this.map.addLayer({
      id: options.layerId + "Circle",
      type: "circle",
      source: options.layerId,
      paint: {
        "circle-radius": 6,
        "circle-color": "#B42222",
      },
      filter: ["==", "$type", "Point"],
    });

    this.map.addLayer({
      id: options.layerId + "Line",
      type: "line",
      source: options.layerId,
      layout: {
        "line-join": "round",
        "line-cap": "round",
      },
      paint: {
        "line-color": "#ffff00",
        "line-width": 5,
        // "line-dasharray": [0, 0]
      },
      filter: ["==", "$type", "LineString"],
    });

    if (!options.fillColor) {
      options.fillColor = "#E8D072";
    }
    this.map.addLayer({
      id: options.layerId,
      type: "fill",
      source: options.layerId,
      // layout: {
      //   "line-join": "round",
      //   "line-cap": "round"
      // },
      paint: {
        "fill-color": options.fillColor,
        "fill-opacity": 0.8,
      },
      filter: ["==", "$type", "Polygon"],
    });
    // this.map.addLayer({
    //   id: "layerFill",
    //   type: "fill",
    //   source: options.layerId,
    //   metadata: {
    //     // 元数据（可选，用于为 layer 附加任意的属性。为避免冲突，建议添加前缀，如 mapbox:）
    //     "mapbox:name": "test",
    //   },
    //   layout: {},
    //   paint: {
    //     "fill-color": "#ff0000", // 填充的颜色（可选，默认值为 #000000。如果设置了 fill-pattern，则 fill-color 将无效）
    //     "fill-opacity": 0,
    //     // "fill-outline-color": "#ffff00"
    //     // "fill-color": {
    //     //   "type": "identity",
    //     //   "property": "valueColor"
    //     // },
    //     "fill-outline-color": {
    //       type: "identity",
    //       property: "outlineColor",
    //     },
    //   },
    //   filter: ["==", "$type", "Polygon"],
    // });
    // this.map.addSource(options.layerId + "_label", {
    //   type: "geojson",
    //   data: turf.featureCollection(dataObj.pointLabel),
    // });
    // const _self = this;
    // 拖拽同步
    // this.map.on("dragend", function () {
    //   const mapX = _self.map.getCenter().lng;
    //   const mapY = _self.map.getCenter().lat;
    //   this.lngLAt = [mapX, mapY];
    //   bus.$emit("dragend", [mapX, mapY]);
    // });
    // this.map.addLayer({
    //   id: options.layerId + "_label",
    //   type: "symbol",
    //   source: options.layerId + "_label",
    //   layout: {
    //     "text-field": [
    //       "format",
    //       ["upcase", ["get", "class_name"]],
    //       {
    //         "font-scale": 1.0,
    //       },
    //       "\t\t\t\t\t",
    //       {},
    //       ["upcase", ["get", "confidence"]],
    //       {
    //         "font-scale": 1.0,
    //       },
    //     ],

    //     "text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"],
    //     "text-size": 18,
    //     "text-allow-overlap": true,
    //     "text-ignore-placement": true,
    //     "text-offset": [0, -0.8],
    //     "text-anchor": "left",
    //   },
    //   paint: {
    //     "text-color": {
    //       type: "identity",
    //       property: "valueColor",
    //     },
    //   },
    //   filter: ["==", "$type", "Point"],
    // });
    // //获得当前点击得目标
    this.map.on("click", "layerFill", (e) => {
      const bbox = [
        [e.point.x - 5, e.point.y - 5],
        [e.point.x + 5, e.point.y + 5],
      ];
      let renderFeatures = this.map.queryRenderedFeatures(bbox, {
        layers: ["layerFill"],
      });
      let obj = {
        geometry: renderFeatures[0].geometry,
      };
      this.addSelectLayer(obj);
    });
  }
  //加载线
  // addLineString(datas, options) {
  //   const defaultOptions = {
  //     layerId: "mapLineString",
  //     name: "poi_name",
  //     time: "time",
  //     description: "description",
  //     iconImgUrl:
  //       "data: image / png; base64, iVBORw0KGgoAAAANSUhEUgAAACwAAAA4CAYAAACGwxqMAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAARZSURBVHgBzZrPbxtVEMe/ sw5UVBE1LSCQqEghiAOXdVOQ4FA2EoeecCz1TiLxBzg3bk3 / gpS / IO6NQ6UkPeXWTSUuIDc + 8qMqq3IgAloMRA0p8b7OrH/Ubmzvvtl1sx/Jsnf37b6vx / PmzZtnQgq89Z0iv7kglOFgBgaugZFzxU6TJr8CImoiRIOvb / Jxw6 + UmlBCUMBCPRRwxRjj9olLjjE1Ms51Fu7DEivBfUI9ZENAoBW / XLqe9IZEglnoDAtdy1DooAiiDbT + W / YrHwdxbZ24Bt56fdE4ZmdSYgV + 9oJxTuxwX9W4tmMFe5v1FePQGjR + ak + R + 1qVPsc1GukSkVjQFRwDBHPVL8 + tDL82hOMU22WU6COCvZv1qjG0ihxgEC7eLl8YiCADgiUayADD8 / HZJDQpPCj1R4 / BQVeAWDYvYoWiKZxY6z / RExyFLw4vyBsGnrf + vdc9nOqdd9INMvfVaVw6ewbumWm8cfLF6Nzdv / dx9599bN1 / gMaDPWgxhYJo8 + Vz5MMy5bLv3oICEfdV6e1I6Di2fn2I2o + /YffRY2igsDXvVz702y5RwBdQIGKvffJerFjh0tnTUduu9W3pWBkkKSJb9y8o+OazD6wFiIW/9H / A3mELlnDEoHNiYRcKFt9 / U2UtuefyO69BAUevQ9eJkm8F8hNrufzu65ieKsAamio7HNisLSwRQeuLwvQLBcyeegm28Mw343DstZ4oZl + 27 + zIMxSCOXF2xYdnYIlYKC3KZxRFsLWF9 / 63HuFZPaMYu + IYhsxeaZFZUIMItl5yS2dprCyxWDlVNx1etVoLFrE37v0OLZJbqDAIJA43oODGvT9UeYHcU / tpF0qaDldkAigQK1e//dlKtLSVe7SwNzQcmMNNKNndbwtI8hM3/vy3/QX3ddlaBMHvJj+/IOVKI8qH3zodTQizp05G53YfHUSDa+v+w1T5cE9vSK9E+fCnN+/cksweeYbrcdsLc0tRHKZW6ypyjuNQTd57q+acWznYLp8/Jx96M12erSwVzqef+8illY3ZYN+tdA8Hcglq0RIUU/UEaZJ5vNx/YkAwV8QDCs0ycgK7QvXZmvGRbM2vzNV4n2IFx4xoGFaZH1NuvcPCdcv/1BD77edP/baf0flwSFINVyVGKQmo5SyNujhSsGxN8VQo3zLA84PH0MH8uG2x2E0Zb/071zhTUsaadFXzSGl1GLFLJL/yUYPCcAkTRvrIZBdJ8CsXNiYZOaKIwH0kaWu1sXhxo77Ke2qxW1M2cF3k2u2FucSx33rrNtPp28DfXjg/b3OL9TKfp++sIkdAhiq2N1kL7oQ7sUoAPbHhaxSq3XyhE+52oIDCw5JEHyhQVX6Edrgz1uGOK5BVrVhBLViwTZSkLW8Ufo0UqF2inySJkm34GkUqC/eIT5QaWYgVMhEckyhJRLAOX6PIxCW6DNmrTpTQ2JCNS3RoL7FaPWsmTWiOHfkLw8XN+kT+b/EEhgjdVdsknN0AAAAASUVORK5CYII="
  //   };
  //   options = extend(Object.create(defaultOptions), options);
  //   this.removeLayer(options.layerId);
  //   this.removeDataSource(options.layerId);
  //   // map.removelayer("mapLineString");
  //   // map.removesource("mapLineString");
  //   this.map.addSource(options.layerId, {
  //     type: "geojson",
  //     data: datas
  //   });
  //   this.map.addLayer({
  //     id: options.layerId,
  //     type: "line",
  //     source: options.layerId,
  //     layout: {
  //       "line-cap": "round",
  //       "line-join": "round"
  //     },
  //     paint: {
  //       "line-color": {
  //         type: "identity",
  //         property: "valueColor"
  //       },
  //       "line-width": 3
  //     }
  //   });

  //   //获得当前点击得目标
  //   // this.map.on("click", "mapLineString", (e) => {
  //   //   console.log(e)
  //   //   const bbox = [
  //   //     [e.point.x - 5, e.point.y - 5],
  //   //     [e.point.x + 5, e.point.y + 5]
  //   //   ];
  //   //   let renderFeatures = this.map.queryRenderedFeatures(bbox, {
  //   //     layers: ["mapLineString"]
  //   //   }
  //   //   );
  //   //   let obj = {
  //   //     geometry: renderFeatures[0].geometry
  //   //   }
  //   //   this.addSelectLayer(obj)
  //   // });
  // }
  //为图层添加标签颜色
  addTagLayer(feature: any, layerColor: any) {
    // this.map.removeLayer("");
    // this.removeDataSource("show_select");
    let _feature = turf.lineString(feature.geometry.coordinates[0]);

    this.map.addSource(feature.id, {
      type: "geojson",
      data: turf.featureCollection([_feature]),
    });
    this.map.addLayer({
      id: feature.id,
      type: "fill",
      source: feature.id,
      paint: {
        "fill-color": layerColor.fillColor,
        // "fill-color": layerColor.fillColor // 填充的颜色（可选，默认值为 #000000。如果设置了 fill-pattern，则 fill-color 将无效）
        "fill-opacity": 0.5,
        "fill-outline-color": layerColor.borderColor,
        // "fill-outline-width": 3,
      },
      layout: {
        // "fill-join": "round",
        // "fill-cap": "round"
      },
    });
  }

  //删除
  delete() {
    this.draw.getSelectedIds().forEach((element) => {
      this.draw.delete(element);
    });
  }
  //控制图层显隐
  chageLayer(layerId = "mapLineString") {
    var visibility = this.map.getLayoutProperty(layerId, "visibility");

    if (visibility === "visible" || visibility == undefined) {
      this.map.setLayoutProperty(layerId, "visibility", "none");
    } else {
      this.map.setLayoutProperty(layerId, "visibility", "visible");
    }
  }

  // 添加tiff文件
  addTiffLayer(mapObject: any, path: any, bounds: any) {
    mapObject.removeLayer("addLayer");
    mapObject.removeDataSource("addLayer");
    mapObject.map.addLayer({
      id: "addLayer",
      type: "raster",
      source: {
        type: "raster",
        tiles: [
          gateway.factory +
            `/image-server/v1?request=GetTile&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&info={"info":[{"path":"${path}","style":{"stretch":{"externalNodataValue":[0,0,0]}}}]}`,
        ],
        tileSize: 256,
      },
      minzoom: 0,
      maxzoom: 22,
      zoom: 16,
      maxBounds: this.getFitBounds(bounds),
    });
    mapObject.map.fitBounds(this.getFitBounds(bounds), {
      padding: 20,
    });
  }
  getFitBounds(data: any) {
    let bboxPolygon = CoordinateTransformation.mercator2lonlat(data);
    // let bboxPolygon = data;
    let mapbounds = [
      [bboxPolygon.coordinates[0][2][0], bboxPolygon.coordinates[0][2][1]],
      [bboxPolygon.coordinates[0][0][0], bboxPolygon.coordinates[0][0][1]],
    ];
    console.log(mapbounds, "mapbounds");
    return mapbounds;
  }
  // setLayerVisible(layerId) {
  //   let visibility = this.map.getLayoutProperty(layerId, "visibility");
  //   if (visibility === "visible") {
  //     this.map.setLayoutProperty(layerId, "visibility", "none");
  //   } else {
  //     this.map.setLayoutProperty(layerId, "visibility", "visible");
  //   }
  // }
}

function extend(dest, src) {
  for (const i in src) {
    if (dest[i] instanceof Object) {
      extend(dest[i], src[i]);
    } else {
      dest[i] = src[i];
    }
  }
  return dest;
}
export default baseMap;
